﻿using System.Diagnostics;
using System.Text;

namespace SvnLogParser
{
    internal class ProcessRunner
    {
        public ProcessResult Start(ICommand command, int timeout = -1)
        {
            var standardOutput = new StringBuilder();
            var errorOutput = new StringBuilder();

            ProcessResult processResult;

            using (var p = new Process())
            {
                p.StartInfo = new ProcessStartInfo
                {
                    Arguments = command.Arguments,
                    CreateNoWindow = true,
                    ErrorDialog = false,
                    FileName = command.FileName,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    WindowStyle = ProcessWindowStyle.Hidden,
                };

                p.OutputDataReceived += (sender, args) => WriteNotNullOrEmpty(args, standardOutput);
                p.ErrorDataReceived += (sender, args) => WriteNotNullOrEmpty(args, errorOutput);

                p.Start();

                p.BeginErrorReadLine();
                p.BeginOutputReadLine();

                var isTimeout = !p.WaitForExit(timeout);

                if (isTimeout)
                {
                    return new ProcessResult(-1, string.Empty, string.Empty, true);
                }

                var exitCode = p.ExitCode;
                var standard = standardOutput.ToString();
                var error = errorOutput.ToString();

                processResult = new ProcessResult(exitCode, standard, error, false);
            }
            return processResult;
        }

        private static void WriteNotNullOrEmpty(DataReceivedEventArgs args, StringBuilder standardOutput)
        {
            if (!string.IsNullOrEmpty(args.Data))
            {
                standardOutput.AppendLine(args.Data);
            }
        }
    }
}